import json
import math

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

from .api_response import GeneralResponse
from .api_response import PageableResponse
from . import models


# Create your views here.

def index(request):
    return render(request, "index.html")


def hello_world(request):
    data = {
        "title": "hello world",
        "description": "simple demo"
    }
    return JsonResponse(GeneralResponse.of(data), safe=False)


def create_user(request):
    # update only support post
    if request.method != "POST":
        return JsonResponse(GeneralResponse.of("No Support, only POST"))
    else:
        # todo if json content error return err
        content = request.body.decode()
        content = json.loads(content)
        info = content['info']
        # save data
        user = models.UserInfo(
            username=info["username"],
            password=info["password"],
            age=info["age"]
        )
        models.UserInfo.save(user)
    return JsonResponse(GeneralResponse.of(True), safe=False)


def update_user(request, user_id):
    # update only support post
    if request.method != "POST":
        return JsonResponse(GeneralResponse.of("No Support, only POST"))
    else:
        # todo if json content error return err
        content = request.body.decode()
        content = json.loads(content)
        info = content['info']
        # query data
        data = models.UserInfo.objects.get(id=user_id)
        data.username = info["username"]
        data.password = info["password"]
        data.age = info["age"]
        data.save()
    return JsonResponse(GeneralResponse.of(True))


def search_users(request):
    page = int(request.GET.get("page", default=0))
    size = int(request.GET.get("size", default=10))
    # query data
    sql = "select * from hello_world_userinfo limit " + str(page * size) + ", " + str(size)
    data = models.UserInfo.objects.raw(sql)
    # todo id data is null ,return empty
    users = []
    for d in data:
        users.append(queryDataConvertObject(d))
    # count all records
    count = models.UserInfo.objects.count()
    pages = math.ceil(count / size)
    return JsonResponse(
        PageableResponse.of(
            pageSize=size,
            pageIndex=page,
            currentRecords=len(users),
            totalRecords=count,
            totalPages=pages,
            payload=users)
    )


def delete_user(request, user_id):
    # update only support post
    if request.method != "POST":
        return JsonResponse(GeneralResponse.of("No Support, only POST"))
    else:
        # todo ,if not exist return error
        models.UserInfo.objects.filter(id=user_id).delete()
    return JsonResponse(GeneralResponse.of(True))


def queryDataConvertObject(data):
    return {
        'username': data.username,
        'password': data.password,
        'age': data.age,
        'id': data.id
    }
